package com.smartcommunity.job;

import com.smartcommunity.base.common.CacheMap;
import com.smartcommunity.entity.statistic.AccessStatisticEntity;
import com.smartcommunity.service.statistic.AccessStatisticService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author nieming
 * @descrition
 * @date 2020/6/10
 */
@Component
@Slf4j
public class DataAccessStatisticsJob {
    @Autowired
    private AccessStatisticService accessStatisticService;

    @Scheduled(initialDelay = 10 * 1000, fixedDelay = 5 * 60 * 1000)
    public void start() {
        Map<String, Long> tempMap = CacheMap.STATISTICS_MAP.convertToJavaHashMap();
        if (CollectionUtils.isEmpty(tempMap)) {
            log.warn("获取数据接入统计为空......");
            return;
        }
        List<AccessStatisticEntity> insertList = new ArrayList<>();
        List<AccessStatisticEntity> updateList = new ArrayList<>();
        for (Map.Entry<String, Long> entry : tempMap.entrySet()) {
            AccessStatisticEntity accessStatisticEntity = tranlate(entry);
            if(null != accessStatisticEntity){
                if(accessStatisticService.exits(accessStatisticEntity)){
                    updateList.add(accessStatisticEntity);
                }else{
                    insertList.add(accessStatisticEntity);
                }
            }
        }
        if(!CollectionUtils.isEmpty(insertList)){
            accessStatisticService.insertBatch(insertList);
        }
        if(!CollectionUtils.isEmpty(updateList)){
            accessStatisticService.updateBatch(updateList);
        }
    }

    public AccessStatisticEntity tranlate(Map.Entry<String, Long> entry) {
        String[] keyArr = entry.getKey().split("\\|");
        if (keyArr.length != 3) {
            log.error("数据接入统计缓存KEY格式错误,key:{}", entry.getKey());
            return null;
        }
        AccessStatisticEntity accessStatisticEntity = new AccessStatisticEntity();
        String accessDayHour = keyArr[0];
        String[] accessDayHourArr = accessDayHour.split(" ");
        if (accessDayHourArr.length != 2) {
            log.error("数据接入统计缓存KEY格式错误,获取日期失败,key:{}", entry.getKey());
            return null;
        }
        accessStatisticEntity.setAccessDay(accessDayHourArr[0]);
        accessStatisticEntity.setAccessHour(accessDayHourArr[1]);
        accessStatisticEntity.setAccessType(keyArr[1]);
        accessStatisticEntity.setDataType(keyArr[2]);
        accessStatisticEntity.setAccessCount(Long.parseLong(String.valueOf(entry.getValue())));
        accessStatisticEntity.setUpdateTime(new Date());
        return accessStatisticEntity;
    }
}
